'use strict'
class WebProcess {
  constructor (io) {
    this.io = io
    this.RoomManage = require('./roommanage')
    this.sockets = new Map()

    this.RoomManage.on('init', this.initRoom.bind(this))
    this.RoomManage.on('update', this.updateRoom.bind(this))
    this.RoomManage.on('data', this.chatMsg.bind(this))
    this.io.on('connection', this.onConnection.bind(this))
  }
  onConnection (socket) {
    this.sockets.set(socket.id, socket)
    socket.on('Binding', this.onBinding.bind(this, socket))
    // socket.on('Stop', this.onStop.bind(this, socket))
    // socket.on('Start', this.onStart.bind(this, socket))
    socket.on('disconnect', this.onDisconnect.bind(this, socket.id))
  }
  onBinding (socket, obj) {
    socket.join(this._getKey(obj.platform, obj.roomId))
    socket.roomId = obj.roomId
    socket.platform = obj.platform || 'dy'
    this.RoomManage.add(obj.platform, obj.roomId, socket.id)
  }
  // onStop (socket, obj) {
  //   socket.leave(obj.roomId)
  // }
  // onStart (socket, obj) {
  //   socket.join(obj.roomId)
  // }
  onDisconnect (socketId, msg) {
    let socket = this.sockets.get(socketId)
    this.RoomManage.remove(socket.platform, socket.roomId)
    this.sockets.delete(socketId)
  }

  initRoom (platform, roomId, socketId, data) {
    if (this.sockets.has(socketId)) {
      this.sockets.get(socketId)
        .emit('initRoom', data)
    }
  }
  updateRoom (platform, roomId, data) {
    this.io.to(this._getKey(platform, roomId))
      .emit('roomUpdate', {
        info: data
      })
  }
  chatMsg (platform, roomId, data) {
    this.io.to(this._getKey(platform, roomId))
      .emit('chatMsg', {
        msg: data
      })
  }
  _getKey (platform, roomId) {
    platform = platform || 'dy'
    return platform.concat('_').concat(roomId)
  }

}

module.exports = WebProcess
